package com.cjkj.common.core.utils;

public class IDCardValidator {

    private IDCardValidator(){

    }

    private static final int[] WEIGHTS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    private static final char[] CHECK_CODES = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

    public static boolean isValid(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            return false;
        }

        for (int i = 0; i < 17; i++) {
            if (!Character.isDigit(idCard.charAt(i))) {
                return false;
            }
        }

        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += (idCard.charAt(i) - '0') * WEIGHTS[i];
        }

        int checkCodeIndex = sum % 11;
        char checkCode = CHECK_CODES[checkCodeIndex];
        return idCard.charAt(17) == checkCode;
    }

//    public static void main(String[] args) {
//        String idCard = "500225199508015013";
//        if (isValid(idCard)) {
//            System.out.println("身份证号码合法");
//        } else {
//            System.out.println("身份证号码不合法");
//        }
//    }
}
